//
//  ViewController.m
//  CarGame
//
//  Created by Dyoung on 2017/9/9.
//  Copyright © 2017年 Dyoung. All rights reserved.
//

#import "ViewController.h"
#import "OtherCarImageView.h"

@interface ViewController ()

@property (nonatomic,weak)   UIImageView * roadImgView1 ;
@property (nonatomic,weak)   UIImageView * roadImgView2;
@property (nonatomic,weak)   UIImageView * myCar;
@property (nonatomic,strong) NSMutableArray * otherCarArr;
@property (nonatomic,strong) CADisplayLink * runTimer;
@property (nonatomic,weak)   UILabel * numLabel;
@property (nonatomic,strong) UIButton * restartBtn;
@property (nonatomic,weak) UIView * gesView;
@property (nonatomic,weak)  UIButton * leftBtn;
@property (nonatomic,weak) UIButton * rightBtn;


@end

@implementation ViewController
{
    CGFloat _timerInterval;
    CGFloat _speedY;
    CGRect  _originFrame;
    CGFloat _RightCarX;
    CGFloat _leftCarX;
    CGFloat _carLengthTime;
    CGFloat _speedCarY;
    NSInteger _showOtherCarFlag;
    
}
-(NSMutableArray *)otherCarArr
{
    if (!_otherCarArr) {
        _otherCarArr = @[].mutableCopy;
        for (int i = 1; i<10; i++) {
            OtherCarImageView * carImg = [[OtherCarImageView alloc]init];
            carImg.isOnScreen = NO;
            carImg.hidden = YES;
            carImg.image = [UIImage imageNamed:[NSString stringWithFormat:@"car%d",i%5+1]];
            [self.view addSubview:carImg];
            carImg.size = self.myCar.size;
            [_otherCarArr addObject:carImg];
        }
    }
    return _otherCarArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSetUp];
    [self setupSubView];
}

-(void)initSetUp
{
    _speedY = 3;
    _RightCarX = DyScreenWidth/2+10;
    _leftCarX = DyScreenWidth/2-DyScreenWidth/4-20;
    _speedCarY = 6;
}

- (void)setupSubView
{
    
    CGFloat roadH =  DyScreenWidth * 4100/1043;
    CGFloat roadY = DyScreenHeight-roadH;
    _originFrame = CGRectMake(0,-roadH+10, DyScreenWidth,roadH);
    
    //road1
    UIImageView * roadImgView = [[UIImageView alloc]init];
    roadImgView.frame = CGRectMake(0, roadY, DyScreenWidth, roadH);
    self.roadImgView1 = roadImgView;
    roadImgView.image = [UIImage imageNamed:@"bg.jpg"];
    [self.view addSubview:roadImgView];
    
    //road2
    UIImageView * roadImgView2 = [[UIImageView alloc]init];
    roadImgView2.frame = CGRectMake(0, roadY-roadH, DyScreenWidth, roadH);
    roadImgView2.image = self.roadImgView1.image;
    self.roadImgView2 = roadImgView2;
    [self.view addSubview:roadImgView2];
    
    //myCar;
    CGFloat carW = DyScreenWidth/4;
    CGFloat carH = carW * 496/264;
    CGFloat carY = DyScreenHeight - carH - 50;
    UIImageView * myCar = [[UIImageView alloc]init];
    myCar.frame = CGRectMake(_RightCarX, carY, carW, carH);
    self.myCar = myCar;
    myCar.image = [UIImage imageNamed:@"myCar"];
    [self.view addSubview:myCar];
    _carLengthTime = carH/_speedCarY*2.5;
    
    //分数显示：
    CGFloat w = 100;
    UILabel * scoreLabel = [[UILabel alloc]initWithFrame:CGRectMake(DyScreenWidth/2-w+5,24,w,40)];
    scoreLabel.textAlignment = 2;
    [self.view addSubview:scoreLabel];
    scoreLabel.font  = [UIFont boldSystemFontOfSize:25];
    scoreLabel.text = @"GET :";
    scoreLabel.textColor  = [UIColor redColor];
    
    //
    UILabel * numLabel = [[UILabel alloc]initWithFrame:CGRectMake(DyScreenWidth/2+5, 24, w, 40)];
    self.numLabel = numLabel;
    numLabel.textColor = [UIColor redColor];
    numLabel.textAlignment = 0;
    [self.view addSubview:numLabel];
    numLabel.font  = [UIFont boldSystemFontOfSize:25];

    
    //添加手势：
    UIView * gesView = [[UIView alloc]initWithFrame:self.view.bounds];
    self.gesView = gesView;
    gesView.backgroundColor = [UIColor colorWithWhite:0 alpha:0];
    [self.view addSubview:gesView];
    gesView.userInteractionEnabled = YES;
    UITapGestureRecognizer * moveTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(moveTapAction:)];
    [gesView addGestureRecognizer:moveTap];
    
    //restart
    CGFloat btnW = 35;
    UIButton * restartBtn = [[UIButton alloc]initWithFrame:CGRectMake(DyScreenWidth-btnW-15, 24, btnW, btnW)];
    self.restartBtn = restartBtn;
    [restartBtn setImage:[UIImage imageNamed:@"restart"] forState:UIControlStateNormal];
    [self.view addSubview:restartBtn];
    restartBtn.hidden = YES;
    [restartBtn addTarget:self action:@selector(restartAction) forControlEvents:UIControlEventTouchUpInside];

    //防止汽车跑到按钮上去：
    [self otherCarArr];
    
    //左右按钮：
    CGFloat controlBtnW = 70;
    CGFloat leftSpace = 50;
    UIButton * leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(leftSpace,DyScreenHeight-controlBtnW-20, controlBtnW, controlBtnW)];
    self.leftBtn = leftBtn;
    [leftBtn setImage:[UIImage imageNamed:@"left"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftRightBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftBtn];
    leftBtn.tag = 1;
    
    UIButton * rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(DyScreenWidth-controlBtnW-leftSpace, DyScreenHeight-controlBtnW-20, controlBtnW, controlBtnW)];
    self.rightBtn = rightBtn;
    [rightBtn setImage:[UIImage imageNamed:@"right"] forState:UIControlStateNormal];
    [self.view addSubview:rightBtn];
    [rightBtn addTarget:self action:@selector(leftRightBtn:) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.tag = 2;
    
    
    //计时器：
    CADisplayLink * runTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(runTimerAction)];
    [runTimer addToRunLoop:[NSRunLoop currentRunLoop]
                   forMode:NSDefaultRunLoopMode];
    self.runTimer  = runTimer;

    
    
}

- (void)leftRightBtn:(UIButton *)btn
{
    if (btn.tag == 1) {
        self.myCar.x = _leftCarX;
    }
    else{
        self.myCar.x = _RightCarX;
    }
}



/**
 * 移动赛车的方法:
 */
- (void)moveTapAction:(UITapGestureRecognizer *)tap
{
    if (tap.state == UIGestureRecognizerStateEnded){
        CGPoint gesPoint = [tap locationInView:self.view];
        if (gesPoint.x<DyScreenWidth/2) {
            self.myCar.x = _leftCarX;
        }
        else{
            self.myCar.x = _RightCarX;
        }
    }
    
}

/**
 * 定时器方法：
 */
- (void)runTimerAction{
    
    [self transferBgView];
    [self showOtherCar];
    [self transferOtherCar];
}

/**
 * 重来游戏：
 */
- (void)restartAction
{
    self.restartBtn.hidden = YES;
    self.leftBtn.enabled = YES;
    self.rightBtn.enabled = YES;
    self.gesView.userInteractionEnabled = YES;
    for (OtherCarImageView * otherCarImgView in self.otherCarArr) {
        if (otherCarImgView.isOnScreen) {
            otherCarImgView.hidden = YES;
            otherCarImgView.isOnScreen = NO;
        }
    }
    _showOtherCarFlag = 0;//重新开始计。
    self.runTimer =[CADisplayLink displayLinkWithTarget:self selector:@selector(runTimerAction)];
    [self.runTimer addToRunLoop:[NSRunLoop currentRunLoop]
                   forMode:NSDefaultRunLoopMode];
}


/**
 * 背景移动
 */
- (void)transferBgView
{
    
    static int i;
    if (i == 0) {//图片1 - 移动
        [UIView animateWithDuration:_timerInterval animations:^{
            if (self.roadImgView1.y>-_speedY) {
                self.roadImgView2.hidden = NO;
                self.roadImgView2.frame = _originFrame;
                i = 1;
            }
            self.roadImgView1.y += _speedY;
            
            //调整图片2的移动
            if (self.roadImgView2.y<DyScreenHeight) {
                self.roadImgView2.y+= _speedY;
            }
            if (self.roadImgView2.y>DyScreenHeight) {
                self.roadImgView2.hidden = YES;
            }
        }];
    }else{//图片2 - 移动
        [UIView animateWithDuration:_timerInterval animations:^{
            if (self.roadImgView2.y>_speedY) {
                self.roadImgView1.hidden = NO;
                self.roadImgView1.frame = _originFrame;
                i = 0;
            }
            self.roadImgView2.y += _speedY;
            
            //调整图片1的移动。
            if (self.roadImgView1.y<DyScreenHeight) {
                self.roadImgView1.y+= _speedY;
            }
            if (self.roadImgView1.y>DyScreenHeight) {
                self.roadImgView1.hidden = YES;
            }
        }];
    }
}


/**
 * 出现对方汽车：
 */
- (void)showOtherCar
{
    //对面出现车辆：
    if ((_showOtherCarFlag % (int)_carLengthTime) == 0) {
        for (OtherCarImageView * carImgView in self.otherCarArr) {
            if (!carImgView.isOnScreen) {
                carImgView.hidden = NO;
                carImgView.isOnScreen = YES;
                CGFloat x = arc4random()%2?_leftCarX:_RightCarX;
                carImgView.x = x;
                carImgView.y = -200;
                break;
            }
        }
    }
    _showOtherCarFlag++;
    
    //更新分数：
    self.numLabel.text = [NSString stringWithFormat:@"%ld 🏁",_showOtherCarFlag/50];
    
}


/**
 * 移动汽车：
 **/
- (void)transferOtherCar
{
    for (UIView * subView in self.view.subviews) {
        if ([subView isKindOfClass:[OtherCarImageView class]]) {
            OtherCarImageView * carImgView = (OtherCarImageView *)subView;
            if (carImgView.isOnScreen) {
                
                if (carImgView.y<DyScreenHeight) {
                    carImgView.y += _speedCarY;
                }else{
                    //移除汽车：
                    carImgView.isOnScreen = NO;
                    carImgView.hidden = YES;
                }
                //检查车子碰撞情况：
                CGRect judgeFrame = CGRectMake(_myCar.x, _myCar.y+30, _myCar.width, _myCar.height-60);
                if (CGRectIntersectsRect(carImgView.frame,judgeFrame)) {
                    [self.runTimer invalidate];
                    [self alertBytitle:[NSString stringWithFormat:@"Congratulations.You've got %@. Do you want to try again?",self.numLabel.text] message:nil submitBlock:^{
                        [self restartAction];
                    } cancelBlock:^{
                        self.restartBtn.hidden = NO;
                        self.gesView.userInteractionEnabled = NO;
                        self.leftBtn.enabled = NO;
                        self.rightBtn.enabled = NO;
                    }];
                    break;
                }

            }
        }
    }
}



@end
